//
//  AvailableNetWorking.m
//  宏铭科技
//
//  Created by 宏铭科技 on 16/7/26.
//  Copyright © 2016年 程超. All rights reserved.
//

#import "AvailableNetWorking.h"
#import "MJ_UserLoginViewModel.h"
#import "UIViewController+CurrentController.h"
#import "LoginViewController.h"

typedef void(^IsLoginBlock)(BOOL isLogin);
@implementation AvailableNetWorking
//计算时间，返回是否重新登录block
+ (void)calulateTimeRangeWithBlock:(IsLoginBlock)isLogin {
    NSDate *lastDate = [UserDefaults objectForKey:@"timeRange"];
    //如果为nil，则直接进入，首次请求必定会存在一个时间节点
    if (lastDate == nil) {
        [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
        isLogin(YES);
    }else {
        NSDate *currentDate = [NSDate date];
        NSTimeInterval start = [lastDate timeIntervalSince1970]*1;
        NSTimeInterval end = [currentDate timeIntervalSince1970]*1;
        NSTimeInterval value = end - start;
        TGLog(@"time Range = %zd",(NSInteger)value);
        [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
        //如果当前时间和之前保存时间超过30分钟，则判断掉线，为用户进行自动登录操作,没有则继续操作，并重新存入当前时间
        if ((NSInteger)value > 1800) {
            isLogin(NO);
        }else{
            isLogin(YES);
            [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
            
        }
    }
}

+(void)postWithUrl:(NSString *)url params:(NSDictionary *)params successHandler:(SuccessBlock)success falureHandler:(FailureBlock)failure{
    
    [self calulateTimeRangeWithBlock:^(BOOL isLogin) {
        if (!isLogin) {
            MJ_UserLoginViewModel *viewModel = [[MJ_UserLoginViewModel alloc] init];
            [viewModel autoLoginWithResult:^(BOOL result) {
                if (!result) {
                    [self pushToLoginViewController];
                }else{
                    [self postWithUrl:url requestParams:params successHander:success failureHander:failure];
                }
            }];
        }else{
            [self postWithUrl:url requestParams:params successHander:success failureHander:failure];
        }
    }];
    
}

+(void)getWithUrl:(NSString *)url params:(NSDictionary *)params successHandler:(SuccessBlock)success falureHandler:(FailureBlock)failure{
    
    [self calulateTimeRangeWithBlock:^(BOOL isLogin) {
        
        if (!isLogin) {
            MJ_UserLoginViewModel *viewModel = [[MJ_UserLoginViewModel alloc] init];
            [viewModel autoLoginWithResult:^(BOOL result) {
                if (!result) {
                    [self pushToLoginViewController];
                }else{
                    [self getWithUrl:url requestParams:params successHander:success failureHander:failure];
                    
                }
            }];
        }else{
            [self getWithUrl:url requestParams:params successHander:success failureHander:failure];
        }
    }];
}

+ (void)uploadDataWithParameter:(NSDictionary *)parameter data:(NSData *)data progress:(ProgressBlock)progressBlock successHander:(SuccessBlock)success failureHander:(FailureBlock)failure {
    [self calulateTimeRangeWithBlock:^(BOOL isLogin) {
        if (!isLogin) {
            MJ_UserLoginViewModel *viewModel = [[MJ_UserLoginViewModel alloc] init];
            [viewModel autoLoginWithResult:^(BOOL result) {
                if (!result) {
                    [self pushToLoginViewController];
                }else{
                    [self uploadWithParameter:parameter data:data progress:progressBlock successHander:success failureHander:failure];
                }
            }];
        }else{
            [self uploadWithParameter:parameter data:data progress:progressBlock successHander:success failureHander:failure];
        }
    }];
}


//跳转至登录界面
+ (void)pushToLoginViewController {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录超时，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[MJ_UserMessage sharedInstance] userLogOut];
        [UIApplication sharedApplication].keyWindow.rootViewController = [LoginViewController new];
    }];
    [alert addAction:action];
    [[UIViewController currentViewController] presentViewController:alert animated:YES completion:nil];
}

@end
